package org.chw.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.chw.netty.handler.EchoClientHandler;

/**
 * @ClassName: EchoClient
 * @Description: 回声客户端
 * @Autor: Vincent.Chen
 * @Create: 2018/6/8 16:37
 * @Version: 1.0
 **/
public class EchoClient {
    private final int port;
    private final String host;

    public EchoClient(String host, int port) {
        this.port = port;
        this.host = host;
    }

    public void start() throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();  //创建 Bootstrap
        try {
            bootstrap.group(eventLoopGroup) //指定 EventLoopGroup 来处理客户端事件
                    .channel(NioSocketChannel.class) //使用的 channel 类型是一个用于 NIO 传输
                    .remoteAddress(host, port)  //设置服务器的 InetSocketAddress
                    .handler(new ChannelInitializer<SocketChannel>() {  //当建立一个连接和一个新的通道时，创建添加到 EchoClientHandler 实例 到 channel pipeline
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            socketChannel.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect().sync();   //连接到远程;等待连接完成
            channelFuture.channel().closeFuture().sync();   //阻塞直到 Channel 关闭
        } finally {
            eventLoopGroup.shutdownGracefully().sync(); //调用 shutdownGracefully() 来关闭线程池和释放所有资源
        }
    }
}
